package com.dom.invoapp.modular.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dom.common.constants.ConstantError;
import com.dom.common.enums.CancelStatEnum;
import com.dom.common.enums.PubStatEnum;
import com.dom.common.enums.PurcOrderStatEnum;
import com.dom.common.enums.VerfyStatEnum;
import com.dom.common.exception.ServiceException;
import com.dom.common.model.standard.ModelHead;
import com.dom.common.model.vo.apply.*;
import com.dom.common.utils.BeanUtil;
import com.dom.common.utils.DateTool;
import com.dom.invoapp.dao.entity.TpPurcCredDetailFlow;
import com.dom.invoapp.dao.entity.TpPurcCredFlow;
import com.dom.invoapp.dao.service.ITTradeDateService;
import com.dom.invoapp.dao.service.ITpPurcCredDetailFlowService;
import com.dom.invoapp.dao.service.ITpPurcCredFlowService;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description 采购单服务
 * @Author xllei
 * @Date 2018/12/15 11:31 AM
 * @Version 1.0
 **/
@Service
@Slf4j
public class PurcCredService {
    @Autowired
    private ITTradeDateService tradeDateService;
    @Autowired
    private ITpPurcCredFlowService purcCredFlowService;
    @Autowired
    private ITpPurcCredDetailFlowService purcCredDetailFlowService;

    /**
     * 分页查询采购单
     * @param p059R
     * @return
     */
    public Page findByPager(P059R p059R) {
        Page<TpPurcCredFlow> pager = new Page<>();
        pager.setCurrent(p059R.getPn());
        pager.setSize(p059R.getPs() == 0 ? 20 : p059R.getPs());

        Wrapper<TpPurcCredFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", p059R.getMemCode());

        if (ObjectUtil.isNotNull(p059R.getMakerId())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("docu_make_id", p059R.getMakerId());
        }
        if (ObjectUtil.isNotNull(p059R.getSuppCode())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("supp_code", p059R.getSuppCode());
        }
        if (ObjectUtil.isNotNull(p059R.getStorCode())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("stor_code", p059R.getStorCode());
        }
        if (ObjectUtil.isNotNull(p059R.getStat())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("stat", p059R.getStat());
        }
        if (ObjectUtil.isNotNull(p059R.getVerfyStat())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("verfy_stat", p059R.getVerfyStat());
        }
        if (ObjectUtil.isNotNull(p059R.getCancelStat())) {
            (wrapper.isEmptyOfWhere() ? wrapper : wrapper.and()).eq("cancel_stat", p059R.getCancelStat());
        }

        wrapper.and().between("make_date", p059R.getExchStartDate(), DateTool.getDayLastSecondTime(p059R.getExchEndDate()));
//        wrapper.and().between("deli_date", p059R.getDeliStartDate(), p059R.getDeliEndDate());

        return purcCredFlowService.selectPage(pager, wrapper);

    }

    /**
     * 采购单登记
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer insertPurcCred(P050R request) {
        TpPurcCredFlow credFlow = buildPurcCredFlow(request);

        //新增采购单
        boolean credResult = purcCredFlowService.insert(credFlow);
        if (!credResult) {
            log.warn("采购单录入失败");
            throw new ServiceException(ConstantError.DATAERROR);
        }

        List<TpPurcCredDetailFlow> credDetailFlows = convert2EntityList(request.getCredDetailData(), credFlow);

        //新增采购单明细
        boolean detailResult = purcCredDetailFlowService.insertBatch(credDetailFlows);
        if (!detailResult) {
            log.warn("采购单明细录入失败");
            throw new ServiceException(ConstantError.DATAERROR);
        }

        return credFlow.getId();
    }

    /**
     * 将采购单明细转位db实体
     * @param sources
     * @param credFlow
     * @return
     */
    private List<TpPurcCredDetailFlow> convert2EntityList(List<CredDetailInfo> sources, TpPurcCredFlow credFlow){
        List<TpPurcCredDetailFlow> dess = new ArrayList<>();
        sources.forEach(credDetailInfo -> {
            TpPurcCredDetailFlow detailFlow = buildPurcCredDetailFlow(credDetailInfo, credFlow);
            dess.add(detailFlow);
        });
        return dess;
    }

    private TpPurcCredFlow buildPurcCredFlow(P050R request) {
        TpPurcCredFlow credFlow = new TpPurcCredFlow();
        BeanUtil.copyPropertiesIgnoreNull(request, credFlow);
        credFlow.setDigest(request.getBillAbstract());
        credFlow.setOrganCode(request.getOrgId());
        credFlow.setDocuMakerId(request.getOperId());
        credFlow.setStat(PurcOrderStatEnum.ORDER_STAT_WAITING.getCode());
        credFlow.setVerfyStat(VerfyStatEnum.VERFY_STAT_CONFIRMING.getCode());
        credFlow.setCancelStat(CancelStatEnum.CANCEL_STAT_NORMAL.getCode());
        credFlow.setExchDate(tradeDateService.getExchDate(0));
        return credFlow;
    }

    private TpPurcCredDetailFlow buildPurcCredDetailFlow(CredDetailInfo credDetailInfo, TpPurcCredFlow credFlow) {
        TpPurcCredDetailFlow purcCredDetailFlow = new TpPurcCredDetailFlow();
        BeanUtil.copyPropertiesIgnoreNull(credDetailInfo, purcCredDetailFlow);

        purcCredDetailFlow.setCredId(credFlow.getId());
        purcCredDetailFlow.setMemCode(credFlow.getMemCode());
        //商品金额
        purcCredDetailFlow.setBal(purcCredDetailFlow.getPrice().multiply(purcCredDetailFlow.getAmount()));
        //计算商品预估进项税
        BigDecimal etsInTax = purcCredDetailFlow.getInTaxRate().multiply(purcCredDetailFlow.getPrice()).multiply(purcCredDetailFlow.getAmount());
        purcCredDetailFlow.setEstInTax(etsInTax);
        //计算商品不含税金额
        purcCredDetailFlow.setNoTaxBal(purcCredDetailFlow.getBal().subtract(etsInTax));

        return purcCredDetailFlow;
    }

    /**
     * 查询采购单信息
     * @param request
     * @return
     */
    public TpPurcCredFlow findPurcCredInfo(P053R request){
        return purcCredFlowService.selectById(request.getCredId());
    }

    /**
     * 根据采购单id查询采购单明细
     * @param credId
     * @return
     */
    public List<TpPurcCredDetailFlow> findCredListByCredId(Integer credId, ModelHead head){
        Wrapper<TpPurcCredDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", head.getMemCode())
                .and().eq("cred_id", credId);

        return purcCredDetailFlowService.selectList(wrapper);
    }

    /**
     * 假删除采购单信息
     * @param request
     * @return
     */
    public Integer delCredPurcInfo(P051R request) {
        TpPurcCredFlow credFlow = purcCredFlowService.selectById(request.getCredId());
        if(ObjectUtil.isNull(credFlow)){
            log.warn("删除未找到匹配数据, id:", request.getCredId());
            throw new ServiceException(ConstantError.ILLQUERYERROR);
        }

        //更新状态为无效
        credFlow.setStat(PubStatEnum.STAT_STOP.getCode());
        boolean result = purcCredFlowService.updateById(credFlow);
        return credFlow.getId();
    }

    /**
     * 查询采购单明细列表
     * @param request
     * @return
     */
    public List<TpPurcCredDetailFlow> findPurcCredDetailList(P069R request){
        Wrapper<TpPurcCredDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode())
                .and().eq("cred_id", request.getCredId())
                .and().eq("stat", PubStatEnum.STAT_NORMAL.getCode())
                .orderBy("id");
        List<TpPurcCredDetailFlow> purcCredDetailFlows = purcCredDetailFlowService.selectList(wrapper);
        return purcCredDetailFlows;
    }

    /**
     * 查询采购单明细-分页查询
     * @param request
     * @return
     */
    public Page<TpPurcCredDetailFlow> findPurcCredDetailPager(P069R request){
        Page<TpPurcCredDetailFlow> pager = new Page<>();
        pager.setSize(request.getPs() == 0 ? 20 : request.getPs());
        pager.setCurrent(request.getPn());

        Wrapper<TpPurcCredDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode())
                .and().eq("cred_id", request.getCredId())
                .and().eq("stat", PubStatEnum.STAT_NORMAL.getCode())
                .orderBy("id");

        return purcCredDetailFlowService.selectPage(pager, wrapper);
    }

    /**
     * 修改采购单信息
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updatePurcCredAndDetail(P052R request) {
        TpPurcCredFlow purcCredFlow = purcCredFlowService.selectById(request.getCredId());
        if(ObjectUtil.isNull(purcCredFlow)){
            log.warn("未找到匹配的采购单记录 credId:", request.getCredId());
            throw new ServiceException(ConstantError.ILLQUERYERROR);
        }

        BeanUtil.copyPropertiesIgnoreNull(request, purcCredFlow);
        purcCredFlow.setMtime(new Date());

        boolean result = purcCredFlowService.updateById(purcCredFlow);

        Wrapper<TpPurcCredDetailFlow> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", request.getMemCode())
                .and().eq("cred_id", purcCredFlow.getId())
                .and().eq("stat", PubStatEnum.STAT_NORMAL.getCode())
                .orderBy("id", true);
        List<TpPurcCredDetailFlow> purcCredDetailFlows = purcCredDetailFlowService.selectList(wrapper);
        purcCredDetailFlows.forEach(entity->{
            entity.setStat(PubStatEnum.STAT_STOP.getCode());
            entity.setMtime(new Date());
        });
        //批量更新采购单明细状态为作废
        boolean batchResult = purcCredDetailFlowService.updateBatchById(purcCredDetailFlows);
        if(!batchResult){
            log.warn("legacy采购单明细更新失败", batchResult);
            throw new ServiceException(ConstantError.DATAERROR);
        }

        //新增采购单明细
        List<TpPurcCredDetailFlow> credDetailFlows = convert2EntityList(request.getCredDetailInfos(), purcCredFlow);

        boolean detailResult = purcCredDetailFlowService.insertBatch(credDetailFlows);
        if (!detailResult) {
            log.warn("采购单明细录入失败");
            throw new ServiceException(ConstantError.DATAERROR);
        }
        return purcCredFlow.getId();
    }


    public static void main(String[] args){
        Date date1 = DateUtil.parse("2018-12-17");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);

        String dateStr = DateUtil.format(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
//        String datestr = sdf.format(cal.getTime());
//
//        System.out.println(datestr);
        System.out.println(dateStr);
    }
}
